//
//  CodaBarScanViewController.m
//  QS
//
//  Created by Centling on 14-4-30.
//  Copyright (c) 2014年 seas.cheng. All rights reserved.
//

#import "CodaBarScanViewController.h"
#import "QTProductDetailViewController.h"
#import "QTScanWebViewController.h"


#define IS_IHONE4 ([UIScreen mainScreen].bounds.size.height == 480)

@interface CodaBarScanViewController ()

@end

@implementation CodaBarScanViewController

@synthesize scanView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden=YES;
}




- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    reader.readerDelegate = self;
    //非全屏
    //    reader.wantsFullScreenLayout = NO;
    //隐藏底部控制按钮
    reader.showsZBarControls = NO;
    //设置自己定义的界面
    [self setOverlayPickerView:reader];
    ZBarImageScanner *scanner = reader.scanner;
    [scanner setSymbology: ZBAR_I25
                   config: ZBAR_CFG_ENABLE
                       to: 0
     ];
    //    [self presentModalViewController: reader
    //
    //                            animated: YES];
    [self addChildViewController:reader];
    reader.view.frame = self.scanView.frame;
    [self.view addSubview:reader.view];    //    [reader release];
    //    zBarReaderView.readerDelegate = self;
    //
    //    [zBarReaderView start];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//取消button方法

- (void)dismissOverlayView:(id)sender{
    
    //    [self dismissModalViewControllerAnimated: YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

//图片button方法
- (void)selectPicture:(id)sender{
    
    if (AlbumView == nil) {
        AlbumView = [[ZBarReaderController alloc] init];
    }
    AlbumView.readerDelegate = self;
    AlbumView.showsHelpOnFail = NO;
    
    //指定图片来源
    //UIImagePickerControllerSourceTypePhotoLibrary：表示显示所有的照片。
    //UIImagePickerControllerSourceTypeCamera：表示从摄像头选取照片。
    //UIImagePickerControllerSourceTypeSavedPhotosAlbum：表示仅仅从相册中选取照片。
    if ([ZBarReaderController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]){
        AlbumView.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
    
    [AlbumView.scanner setSymbology:ZBAR_I25 config:ZBAR_CFG_ENABLE to:0];
    
    [self presentViewController:AlbumView animated:YES completion:nil];
    //    [self dismissModalViewControllerAnimated: YES];
    //    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController*)reader didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    NSLog(@"info=%@",info);
    // 得到条形码结果
    id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    
    for(symbol in results) break;

    NSString *encodedResultStr = [symbol.data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"=======>>>>>%@", symbol.data);
    NSLog(@"=======>>>>>encoded %@", encodedResultStr);
    if ((encodedResultStr != nil) || (encodedResultStr.length != 0))
    {
        
        // ... todo
//        QTProductDetailViewController* productDetailViewController = [[QTProductDetailViewController alloc ] init];
//        productDetailViewController.barCode=encodedResultStr;
//        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
//        self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
//        [self.navigationItem setBackBarButtonItem:backItem];
//        [self.navigationController.navigationBar setHidden:NO];
//        [self.navigationController pushViewController:productDetailViewController animated:YES];
        
        QTScanWebViewController* scanWebViewVC = [[QTScanWebViewController alloc ] init];
        scanWebViewVC.barCode=encodedResultStr;
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
        self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
        [self.navigationItem setBackBarButtonItem:backItem];
        [self.navigationController.navigationBar setHidden:NO];
        [self.navigationController pushViewController:scanWebViewVC animated:YES];
    }

    if (AlbumView != nil) {
        // 图片选取页面退出
        AlbumView = nil;
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

//- (void) readerView: (ZBarReaderView*) view
//     didReadSymbols: (ZBarSymbolSet*) syms
//          fromImage: (UIImage*) img
//{
//    // do something useful with results
//    for(ZBarSymbol *sym in syms) {
////        self.resultTextView.text = sym.data;
//        [zBarReaderView stop];
//        break;
//    }
//}

-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void) readerControllerDidFailToRead:(ZBarReaderController *)reader withRetry:(BOOL)retry
{
    if (retry) {
        //retry == YES 选择图片为非二维码
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@""
                                                      message:[NSString stringWithFormat:@"您选择的二维码不正确，请重新选择", nil]
                                                     delegate:self
                                            cancelButtonTitle:nil
                                            otherButtonTitles:@"确定", nil];
        [alert show];
        
        if (![self.parentViewController isBeingDismissed]) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
    else {//if retry is NO, must dismiss the reader returning
        [reader dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)setOverlayPickerView:(ZBarReaderViewController *)reader
{
    
    // scancrop width/height = 220
    // topedge = 127
    // leftedge = (320-220)/2=50
    // rightedge = 50+220=270
    // bottomedge = 127+220=347
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    
    CGFloat scanCropWidth = 220;
    CGFloat scanCropHeight = 220;
    CGFloat topEdge;
    if (IS_IHONE4)
    {
        topEdge = 80;
    }
    else
    {
        topEdge = 127;
    }
    
    
    CGFloat leftEdge = (screenWidth-scanCropWidth)/2.0;
    CGFloat rightEdge = leftEdge+scanCropWidth;
    CGFloat bottomEdge = topEdge+scanCropHeight;
    CGFloat lineLength = 20;
    CGFloat lineWidth = 4;
    
    CGFloat buttonOrignX = 60;
    CGFloat buttonOrignY;
    if (IS_IHONE4)
    {
        buttonOrignY = 380;
    }
    else
    {
        buttonOrignY = 468;
    }
    CGFloat buttonHeight = 30;
    CGFloat buttonWidth = 84;
    
    
    //    UIColor *lineColor = [UIColor colorWithRed:88 green:224 blue:72 alpha:1];
    UIColor *lineColor = [UIColor greenColor];
    CGFloat backviewAlpha = 0.3;
    
    UIColor *borderColor = [UIColor lightGrayColor];
    CGFloat borderWidth = 1;
    
    //清除原有控件
    
    for (UIView *temp in [reader.view subviews]) {
        
        for (UIButton *button in [temp subviews]) {
            
            if ([button isKindOfClass:[UIButton class]]) {
                
                [button removeFromSuperview];
                
            }
            
        }
        
        for (UIToolbar *toolbar in [temp subviews]) {
            
            if ([toolbar isKindOfClass:[UIToolbar class]]) {
                
                [toolbar setHidden:YES];
                
                [toolbar removeFromSuperview];
                
            }
            
        }
        
    }
    
    //画中间的基准线
    
    //    UIView* line = [[UIView alloc] initWithFrame:CGRectMake(40, 220, 240, 1)];
    //
    //    line.backgroundColor = [UIColor redColor];
    //
    //    [reader.view addSubview:line];
    
    //    [line release];
    
    //最上部view
    
    UIView* upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, topEdge)];
    
    upView.alpha = backviewAlpha;
    
    upView.backgroundColor = [UIColor blackColor];
    
    [reader.view addSubview:upView];
    
    //    //用于说明的label
    //
    //    UILabel * labIntroudction= [[UILabel alloc] init];
    //
    //    labIntroudction.backgroundColor = [UIColor clearColor];
    //
    //    labIntroudction.frame=CGRectMake(30, 320, 320, 120);
    //
    //    labIntroudction.numberOfLines=1;
    //
    //    labIntroudction.textColor=[UIColor whiteColor];
    //
    //    labIntroudction.text=@"将二维码/条码放入框内，即可自动扫描";
    //    [labIntroudction setFont:[UIFont boldSystemFontOfSize:15]];
    //
    //    [upView addSubview:labIntroudction];
    
    //    [labIntroudction release];
    //
    //    [upView release];
    
    //左侧的view
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, topEdge, leftEdge, bottomEdge-topEdge)];
    
    leftView.alpha = backviewAlpha;
    
    leftView.backgroundColor = [UIColor blackColor];
    
    [reader.view addSubview:leftView];
    
    
    // 左上角
    UIView* line1 = [[UIView alloc] initWithFrame:CGRectMake(leftEdge, topEdge, lineLength, lineWidth)];
    
    line1.backgroundColor = lineColor;
    
    [reader.view addSubview:line1];
    
    UIView* line2 = [[UIView alloc] initWithFrame:CGRectMake(leftEdge, topEdge, lineWidth, lineLength)];
    
    line2.backgroundColor = lineColor;
    
    [reader.view addSubview:line2];
    
    // 左边线条
    UIView* leftBorder = [[UIView alloc] initWithFrame:CGRectMake(leftEdge, topEdge, borderWidth, bottomEdge-topEdge)];
    
    leftBorder.backgroundColor = borderColor;
    
    [reader.view addSubview:leftBorder];
    
    // 右边线条
    UIView* rightBorder = [[UIView alloc] initWithFrame:CGRectMake(rightEdge, topEdge, borderWidth, bottomEdge-topEdge)];
    
    rightBorder.backgroundColor = borderColor;
    
    [reader.view addSubview:rightBorder];
    
    // 顶部线条
    UIView* topBorder = [[UIView alloc] initWithFrame:CGRectMake(leftEdge, topEdge, rightEdge-leftEdge, borderWidth)];
    
    topBorder.backgroundColor = borderColor;
    
    [reader.view addSubview:topBorder];
    
    // 底部线条
    UIView* bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(leftEdge, bottomEdge, rightEdge-leftEdge, borderWidth)];
    
    bottomBorder.backgroundColor = borderColor;
    
    [reader.view addSubview:bottomBorder];
    
    
    //    [line release];
    //    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //    CGContextSetStrokeColorWithColor(ctx, [lineColor CGColor]);
    //    CGContextSetLineWidth(ctx, 3.0);
    //
    //    CGContextMoveToPoint(ctx, 41, 101);
    //    CGContextAddLineToPoint(ctx, 41, 150);
    //    CGContextClosePath(ctx);
    //    CGContextStrokePath(ctx);
    //    [leftView release];
    
    //右侧的view
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(rightEdge, topEdge, screenWidth-rightEdge, bottomEdge-topEdge)];
    
    rightView.alpha = backviewAlpha;
    
    rightView.backgroundColor = [UIColor blackColor];
    
    [reader.view addSubview:rightView];
    
    // 右上角
    UIView* line3 = [[UIView alloc] initWithFrame:CGRectMake(rightEdge-lineLength, topEdge, lineLength, lineWidth)];
    
    line3.backgroundColor = lineColor;
    
    [reader.view addSubview:line3];
    
    UIView* line4 = [[UIView alloc] initWithFrame:CGRectMake(rightEdge-lineWidth, topEdge, lineWidth, lineLength)];
    
    line4.backgroundColor = lineColor;
    
    [reader.view addSubview:line4];
    //    [rightView release];
    
    //底部view
    
    UIView * downView = [[UIView alloc] initWithFrame:CGRectMake(0, bottomEdge, screenWidth, screenHeight-bottomEdge)];
    
    downView.alpha = backviewAlpha;
    
    downView.backgroundColor = [UIColor blackColor];
    
    [reader.view addSubview:downView];
    
    // 左下角
    UIView* line5 = [[UIView alloc] initWithFrame:CGRectMake(leftEdge, bottomEdge-lineWidth, lineLength, lineWidth)];
    
    line5.backgroundColor = lineColor;
    
    [reader.view addSubview:line5];
    
    UIView* line6 = [[UIView alloc] initWithFrame:CGRectMake(leftEdge, bottomEdge-lineLength, lineWidth, lineLength)];
    
    line6.backgroundColor = lineColor;
    
    [reader.view addSubview:line6];
    
    // 右下角
    UIView* line7 = [[UIView alloc] initWithFrame:CGRectMake(rightEdge-lineLength, bottomEdge-lineWidth, lineLength, lineWidth)];
    
    line7.backgroundColor = lineColor;
    
    [reader.view addSubview:line7];
    
    UIView* line8 = [[UIView alloc] initWithFrame:CGRectMake(rightEdge-lineWidth, bottomEdge-lineLength, lineWidth, lineLength)];
    
    line8.backgroundColor = lineColor;
    
    [reader.view addSubview:line8];
    
    //    [downView release];
    
    //用于取消操作的button
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    UIImage *cancelButtonImageOrg = [UIImage imageNamed:@"scan-back.png"];
    CGRect countRect = CGRectMake(0.0, 0.0, 20, 20);
    UIGraphicsBeginImageContext(countRect.size);
    [cancelButtonImageOrg drawInRect:countRect];
    UIImage *cancelButtonImageFinal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [cancelButton setImage: cancelButtonImageFinal forState: UIControlStateNormal];
    [cancelButton setTitle:@"返回" forState:UIControlStateNormal];
    cancelButton.tintColor = [UIColor whiteColor];
    
    [cancelButton setImageEdgeInsets: UIEdgeInsetsMake(0, -20, 0, 0)];
    [cancelButton setTitleEdgeInsets: UIEdgeInsetsMake(0, 0, 0, 0)];
    
    
    //    cancelButton.alpha = 0.4;
    cancelButton.backgroundColor = [UIColor blackColor];
    [cancelButton setFrame:CGRectMake(buttonOrignX, buttonOrignY, buttonWidth, buttonHeight)];
    
    
    [cancelButton.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    cancelButton.titleLabel.textColor = [UIColor whiteColor];
    
    [cancelButton addTarget:self action:@selector(dismissOverlayView:)forControlEvents:UIControlEventTouchUpInside];
    
    [reader.view addSubview:cancelButton];
    
    //用于打开图片的button
    
    UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    UIImage *imageButtonImageOrg = [UIImage imageNamed:@"scan-image.png"];
    CGRect countRect2 = CGRectMake(0.0, 0.0, 20, 20);
    UIGraphicsBeginImageContext(countRect.size);
    [imageButtonImageOrg drawInRect:countRect2];
    UIImage *imageButtonImageFinal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [imageButton setImage: imageButtonImageFinal forState: UIControlStateNormal];
    [imageButton setTitle:@"图片" forState:UIControlStateNormal];
    imageButton.tintColor = [UIColor whiteColor];
    
    [imageButton setImageEdgeInsets: UIEdgeInsetsMake(0, -20, 0, 0)];
    [imageButton setTitleEdgeInsets: UIEdgeInsetsMake(0, 0, 0, 0)];
    //    imageButton.alpha = 0.4;
    imageButton.backgroundColor = [UIColor blackColor];
    
    [imageButton setFrame:CGRectMake(screenWidth-buttonWidth-buttonOrignX, buttonOrignY, buttonWidth, buttonHeight)];
    
    
    [imageButton.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    imageButton.titleLabel.textColor = [UIColor whiteColor];
    
    [imageButton addTarget:self action:@selector(selectPicture:)forControlEvents:UIControlEventTouchUpInside];
    
    [reader.view addSubview:imageButton];
}


@end
